package dao;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import javax.imageio.ImageIO;

import model.TileType;

public class TileTypeDao extends Dao {
	private static File TILE_TYPE_FOLDER = new File("resources/tiletypes");
	private static File IMAGE_FOLDER = new File("resources/images");

	private HashMap<String, TileType> cache = new HashMap<String, TileType>();

	public static void main(String[] args) throws IOException {
		TileTypeDao dao = new TileTypeDao();
		TileType[] types = dao.loadAll();
		for (TileType type : types) {
			System.out.println(type.getImageName() + " "
					+ type.getConnections());
		}
	}

	public TileType load(String name) throws IOException {
		if (cache.containsKey(name)) {
			return cache.get(name);
		} else {
			File file = new File(TILE_TYPE_FOLDER, name + ".data");
			if (file.exists() && file.canRead()) {
				TileType type = load(file);
				cache.put(name, type);
				return type;
			}
			return null;
		}
	}

	private TileType load(File file) throws IOException {
		FileReader reader = new FileReader(file);
		BufferedReader buffered = new BufferedReader(reader);
		String line = "";
		String imagename = buffered.readLine();
		int connectioncount = parseInt(buffered.readLine());
		int[][] connections = new int[connectioncount][];
		for (int i = 0; i < connectioncount; i++) {
			connections[i] = parseIntegerList(buffered.readLine());
		}
		TileType type = new TileType(connections, imagename);
		type.setImage(ImageIO.read(new File(IMAGE_FOLDER, imagename)));
		return type;
	}

	public TileType[] loadAll() throws IOException {
		File[] files = TILE_TYPE_FOLDER.listFiles();
		ArrayList<TileType> types = new ArrayList<TileType>();
		for (File file : files) {
			if (file.isFile() && file.canRead()) {
				types.add(this.load(file));
			}
		}
		return types.toArray(new TileType[types.size()]);
	}
}
